package com.iyoudoock.citymine.activity;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.iyoudoock.citymine.BaseActivity;
import com.iyoudoock.citymine.R;
import com.iyoudoock.citymine.activity.order.OrderCenterActivity;
import com.iyoudoock.citymine.activity.setting.AppSettingActivity;
import com.iyoudoock.citymine.activity.user.EditUserInfoActivity;
import com.iyoudoock.citymine.activity.user.LoginActivity;
import com.iyoudoock.citymine.activity.user.PersonCenterActivity;
import com.iyoudoock.citymine.bean.AroundPeopleBean;
import com.iyoudoock.citymine.constants.HttpUtils;
import com.iyoudoock.citymine.constants.Key;
import com.iyoudoock.citymine.constants.Map;
import com.iyoudoock.citymine.constants.Value;
import com.iyoudoock.citymine.utils.MapUtils;
import com.iyoudoock.citymine.utils.SystemUtils;
import com.kvin.toolkit.constants.Interaction;
import com.kvin.toolkit.utils.DialogUtils;
import com.kvin.toolkit.utils.JumpUtils;
import com.kvin.toolkit.utils.ListUtils;
import com.kvin.toolkit.utils.LogUtils;
import com.kvin.toolkit.utils.StringUtils;
import com.kvin.toolkit.utils.TipsUtils;
import com.kvin.toolkit.utils.ToastUtils;
import com.kvin.toolkit.utils.http.JsonHttpResponseHandler;
import com.kvin.toolkit.utils.http.JsonUtils;
import com.kvin.toolkit.utils.system.AnimUtils;
import com.kvin.toolkit.utils.system.NetUtils;
import com.kvin.toolkit.utils.system.PermissionUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MapActivity extends BaseActivity {
    @BindView(R.id.m_map_view)
    MapView mMapView;
    @BindView(R.id.notice_tv)
    TextView noticeTv;
    @BindView(R.id.close_container)
    RelativeLayout closeContainer;
    @BindView(R.id.notice_container)
    LinearLayout noticeContainer;

    @BindView(R.id.location_iv)
    ImageView locationIv;
    @BindView(R.id.refresh_iv)
    ImageView refreshIv;

    @BindView(R.id.map_left_menu)
    DrawerLayout mapLeftMenu;
    @BindView(R.id.book_container)
    LinearLayout bookContainer;


    private BaiduMap mBaiduMap;

    private boolean isFirstLoc = true;
    private LocationClient mLocationClient;

    private String mLatitude;
    private String mLongitude;

    private TextView nameTv;
    private TextView phoneTv;

    private DialogUtils contactUsDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        ButterKnife.bind(this);
    }

    @Override
    public void init() {
        initMenu();
        mJsonUtils = JsonUtils.newInstance();

        registerNetReceiver();
        //init base map
        mMapView.removeViewAt(2);//zoom up or down  view
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        // mBaiduMap.setOnMarkerClickListener(mOnMarkerClickListener);
        mBaiduMap.setTrafficEnabled(true);
        mBaiduMap.setBuildingsEnabled(true);
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomBy(Map.ZOOM_SCALE);// 2公里左右
        mBaiduMap.setMapStatus(msu);

        //init location related
        mBaiduMap.setMyLocationEnabled(true);//
        mLocationClient = new LocationClient(this);
        mLocationClient.registerLocationListener(new OnLocationListener());
        mLocationClient.setLocOption(MapUtils.getOption());//bind location configs

        noticeTv.setText("天津部分地区已经开通回收服务，其他地区将陆续开通        ");

        LogUtils.d("----" + noticeTv.isFocusable());
        refreshIv.setOnClickListener(this);
        locationIv.setOnClickListener(this);
        closeContainer.setOnClickListener(this);
        this.bookContainer.setOnClickListener(this);

        mBaiduMap.setOnMarkerClickListener(mOnMarkerClickListener);

        LogUtils.d("----Map-init-" + this);

    }

    @Override
    public void initDialog() {
        View v = getLayoutInflater().inflate(R.layout.dialog_contact_us, null);
        contactUsDialog = DialogUtils.getInstance(this, v);
        TextView descTv = (TextView) v.findViewById(R.id.desc_tv);
        Button firBtn = (Button) v.findViewById(R.id.fir_btn);
        Button secBtn = (Button) v.findViewById(R.id.sec_btn);
        descTv.setText("你确定要拨打客服电话？");
        firBtn.setText(Value.SERVER_NO);
        secBtn.setText("取消");


        firBtn.setOnClickListener(this);
        secBtn.setOnClickListener(this);

        mTips = TipsUtils.getInstance(this);
        mTips.setCanceledOnTouchOutside(false);
        mTips.setTitle("温馨提示");
        mTips.setOnCancelClickListener(null);//default handle
        mTips.setOnConfirmClickListener(null);

    }

    /**
     * init sliding menu
     */
    private void initMenu() {
        //mapLeftMenu = new SlidingMenu(this);
//        mapLeftMenu.setMode(SlidingMenu.LEFT);
//        mapLeftMenu.setBehindOffset(getResources().getDimensionPixelSize(R.dimen.menu_setting_width));
//        View v = getLayoutInflater().inflate(R.layout.menu_setting, null);
//        mapLeftMenu.setMenu(v);
//        mapLeftMenu.setBehindScrollScale(1.0f);
//
//        //mapLeftMenu.attachToActivity(this, SlidingMenu.SLIDING_WINDOW);
//        mapLeftMenu.showMenu();
//        mapLeftMenu.toggle();

        nameTv = (TextView) mapLeftMenu.findViewById(R.id.name_tv);
        phoneTv = (TextView) mapLeftMenu.findViewById(R.id.phone_tv);

        //set click event
        LogUtils.d("--------" + mapLeftMenu.findViewById(R.id.exit_container));
        mapLeftMenu.findViewById(R.id.exit_container).setOnClickListener(this);
        mapLeftMenu.findViewById(R.id.avatar_container).setOnClickListener(this);
        mapLeftMenu.findViewById(R.id.order_container).setOnClickListener(this);
        mapLeftMenu.findViewById(R.id.favorites_container).setOnClickListener(this);
        mapLeftMenu.findViewById(R.id.black_list_container).setOnClickListener(this);
        mapLeftMenu.findViewById(R.id.mall_container).setOnClickListener(this);
        mapLeftMenu.findViewById(R.id.setting_container).setOnClickListener(this);
        mapLeftMenu.findViewById(R.id.user_info_container).setOnClickListener(this);
        mapLeftMenu.findViewById(R.id.connet_us_container).setOnClickListener(this);
        mapLeftMenu.findViewById(R.id.share_container).setOnClickListener(this);
//        mapLeftMenu.findViewById(R.id.api_container).setOnClickListener(this);
    }


    /**
     * init navigation
     */
    @Override
    public void initNav() {
        setTitle(getString(R.string.app_name));
        setNavBackIcon(R.mipmap.nav_setting);


    }


    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
        updateMenuInfo();
        //initDialog();
        startLocation();
        //checkLoginState();
        mIntent = getIntent();
        if (mIntent != null && mIntent.getIntExtra(Key.Tag.STATE, 0) == Value.Response.SUCCESS) {
            ToastUtils.simpleToast(this, "注册成功，我们将在1~3工作日内为您审核");
        }
        isCARunning = true;

        LogUtils.d("----Map--" + this);
    }

    /**
     * update when login in successfully
     */
    private void updateMenuInfo() {
        mUid = mPersistentUtils.readString(Key.User.UID);
        nameTv.setText(TextUtils.isEmpty(mUid) ? "" : mPersistentUtils.readString(Key.User.NICK_NAME));
        phoneTv.setText(TextUtils.isEmpty(mUid) ? "" : mPersistentUtils.readString(Key.User.TELEPHONE));
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
        isCARunning = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMapView != null) {
            mMapView.onDestroy();
            mMapView = null;
        }
        unregisterNetReceiver();
        //logout();
    }

    @Override
    public void onBackPressed() {
        pressAgainExit();
    }

    /**
     * handle click event here
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.location_iv:
                backToMyLocation();
                break;
            case R.id.refresh_iv:
                searchAroundRecycler();
                break;
            case R.id.close_container:
                noticeContainer.setVisibility(View.GONE);
                break;
            case R.id.exit_container:
                logout();
                break;
            case R.id.avatar_container:
                avatarClick();
                break;
            case R.id.order_container:
                mIntent = new Intent(getActivity(), OrderCenterActivity.class);
                mIntent.putExtra(Key.Tag.FROM, Value.Act.MAP);
                JumpUtils.simpleJump(getActivity(), mIntent);
                break;
            case R.id.favorites_container:
                break;
            case R.id.book_container:
                oneKeyBook();
                break;
            case R.id.black_list_container:
                JumpUtils.simpleJump(getActivity(), BlackListActivity.class);
                break;
            case R.id.mall_container:
                break;
            case R.id.setting_container:
                JumpUtils.simpleJump(getActivity(), AppSettingActivity.class);
                break;
            case R.id.user_info_container:
                JumpUtils.simpleJump(getActivity(), EditUserInfoActivity.class);
                break;
            case R.id.connet_us_container:
                contactUs();
                mapLeftMenu.closeDrawer(Gravity.LEFT);
                break;
            case R.id.share_container:
                JumpUtils.simpleJump(getActivity(), ShareActivity.class);
                break;
            case R.id.fir_btn:
                SystemUtils.call(getActivity(), Value.SERVER_NO);
                break;
            case R.id.sec_btn:
                if (isCARunning)
                    contactUsDialog.dismiss();
                break;
//            case R.id.api_container://use for test api
//                testApi();
//                //ToastUtils.simpleToast(getActivity(),"");
//                break;
        }
    }

    private void testApi() {
        mLongitude = "22.0";
        mLatitude = "23.0";
        this.mMacId = SystemUtils.getMac(this);
        params = HttpUtils.isLogin(mUid, mMacId);
        mJsonUtils.post(HttpUtils.IS_LOGIN_URL, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(JSONObject response) {
                super.onSuccess(response);

            }
        });
    }


    /**
     * one key book
     */
    private void oneKeyBook() {
        String address = mPersistentUtils.readString(Key.User.ADDRESS);
        params = HttpUtils.sendOrder(mUid, "", mLongitude, mLatitude, "3000", "", "", address, "", "");
        mJsonUtils.post(HttpUtils.SEND_ORDER_URL, params, this, Value.Flag.ONE_KEY_BOOK);
    }

    private BaiduMap.OnMarkerClickListener mOnMarkerClickListener = new BaiduMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {

            JumpUtils.jumpWithParams(getActivity(), PersonCenterActivity.class, marker.getExtraInfo());
            return true;
        }
    };

    /**
     * search around recycler
     */
    private void searchAroundRecycler() {
        params = HttpUtils.getAroundRecyclerParams(mUid, mLongitude, mLatitude, "3000", searchType());
        mJsonUtils.post(HttpUtils.AROUND_RECYCLER_URL, params, this, Value.Flag.SEARCH_AROUND_RECYCLER);
    }


    @Override
    public void onSuccess(JSONObject response, String flag) {
        super.onSuccess(response, flag);
        if (response == null) return;

        if (flag.equals(Value.Flag.SEARCH_AROUND_RECYCLER)) {
            handleAroundRecycler(response);
        } else if (flag.equals(Value.Flag.ONE_KEY_BOOK)) {
            try {
                msg = response.getString(Key.Tag.MSG);
                ToastUtils.simpleToast(getActivity(), TextUtils.isEmpty(msg) ? getString(R.string.tip_book_fail) : msg);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else if (flag.equals(Value.Flag.CHECK_LOGIN_STATE)) {
            try {
                state = response.getJSONObject(Key.Tag.STATE).getInt(Key.Tag.LOGIN_STATE);
                if (state != Value.Flag.LOGINED) {
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * handle around recycler
     *
     * @param response
     */
    private void handleAroundRecycler(JSONObject response) {
        try {
            String s = response.getString(Key.Tag.DATA);
            if (TextUtils.isEmpty(s)) return;
            List<AroundPeopleBean> list = JSON.parseArray(s, AroundPeopleBean.class);
            if (ListUtils.isEmpty(list) && isRunning) {
                mTips.setDesc("您的周边有0个回收商！");
                mHandler.sendEmptyMessage(Value.Message.DIALOG_SHOW);
                return;
            }
            LatLngBounds.Builder mBuilder = new LatLngBounds.Builder();
            for (int i = 0; i < list.size(); i++) {
                AroundPeopleBean bean = list.get(i);
                LatLng mLatLng = new LatLng(bean.getLatitude(), bean.getLongitude());
                OverlayOptions options = new MarkerOptions().position(mLatLng).icon(getOverlay(bean.getType())).zIndex(7);

                Marker marker = (Marker) mBaiduMap.addOverlay(options);
                mBundle = new Bundle();
                mBundle.putParcelable(Key.Tag.PEOPLE, bean);
                mBundle.putInt(Key.Tag.FROM, Value.Act.MAP);
                marker.setExtraInfo(mBundle);
                mBuilder.include(marker.getPosition());
            }
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngBounds(mBuilder.build()));
            mTips.setDesc("您的周边有" + list.size() + "个回收商！");
            mHandler.sendEmptyMessage(Value.Message.DIALOG_SHOW);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onFailure(IOException e, String flag) {
        super.onFailure(e, flag);
    }

    /**
     * contact us
     */
    private void contactUs() {
        if (!PermissionUtils.isPermitted(getActivity(), Interaction.Permissions.CALL)) {
            PermissionUtils.requestPermission(getActivity(), Interaction.Permissions.CALL, Interaction.Code.REQUEST_CALL);
        } else {
            if (isCARunning)
                contactUsDialog.show();
        }
    }

    /**
     * avatar click event
     */
    private void avatarClick() {
        String address = mPersistentUtils.readString(Key.User.ADDRESS);
        mUid = mPersistentUtils.readString(Key.User.UID);
        if (StringUtils.isEmpty(mUid)) {
            JumpUtils.simpleJump(getActivity(), LoginActivity.class);
        } else if (StringUtils.isEmpty(address)) {
            JumpUtils.simpleJump(getActivity(), EditUserInfoActivity.class);
        } else {
            JumpUtils.simpleJump(getActivity(), PersonCenterActivity.class);
        }
    }


    /**
     * back to my location
     */
    private void backToMyLocation() {
        if (StringUtils.isEmpty(mLatitude) || StringUtils.isEmpty(mLongitude)) {
            startLocation();
        } else {
            updateLocation(Double.valueOf(mLatitude), Double.valueOf(mLongitude));
        }

    }


    @Override
    public void onBackClick(View view) {
        mUid = mPersistentUtils.readString(Key.User.UID);
        if (TextUtils.isEmpty(mUid)) {
            JumpUtils.simpleJump(getActivity(), LoginActivity.class, AnimUtils.getDefaultBackAnim());
        } else if (mapLeftMenu.isDrawerOpen(Gravity.LEFT)) {
//            mapLeftMenu.showMenu(true);
            mapLeftMenu.closeDrawer(Gravity.LEFT);
        } else {
            mapLeftMenu.openDrawer(Gravity.LEFT);

        }
    }

    private void startLocation() {
        isFirstLoc = true;
        // 开始定位
        if (!PermissionUtils.isPermitted(MapActivity.this, Interaction.Permissions.LOC)) {
            PermissionUtils.requestPermission(MapActivity.this, Interaction.Permissions.LOC, Interaction.Code.REQUEST_LOCATION);
        } else {
            launchLocation();
        } // isFirst = true;
    }

    /**
     * start location
     */
    private void launchLocation() {
        if (!NetUtils.isNetConnected(this)) {
            ToastUtils.simpleToast(getActivity(), "当前没有网络，请检查！");
            return;
        } else if (mBaiduMap != null) {
            //mBaiduMap.setMyLocationEnabled(true);
            if (!mLocationClient.isStarted()) {
                // isFirst = true;
                mLocationClient.start();
            }
        }
    }


    /**
     * 定位SDK监听函数
     */
    public class OnLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null)
                return;
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                mLatitude = String.valueOf(location.getLatitude());
                mLongitude = String.valueOf(location.getLongitude());
                mPersistentUtils.writeString(Key.User.LATITUDE, mLatitude);
                mPersistentUtils.writeString(Key.User.LONGITUDE, mLongitude);
                updateLocation(location.getLatitude(), location.getLongitude());
                uploadLatLng(mLatitude, mLongitude);//upload location info
            }


        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }

        public void onReceivePoi(BDLocation poiLocation) {

        }
    }

    /**
     * update location
     */
    private void updateLocation(double lat, double lon) {
        LatLng ll = new LatLng(lat, lon);
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
        mBaiduMap.animateMapStatus(u);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults == null || grantResults.length < 1) return;

        if (requestCode == Interaction.Code.REQUEST_LOCATION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                launchLocation();
            }
        } else if (requestCode == Interaction.Code.REQUEST_CALL) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
                if (isCARunning)
                    contactUsDialog.show();
        }
    }


    @Override
    public void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        switch (msg.what) {
            case Value.Message.LOGOUT_SUCCESS:
                mapLeftMenu.closeDrawer(GravityCompat.START);
                break;
            case Value.Message.DIALOG_SHOW:
                if (isCARunning)
                    mTips.show();
                break;
        }
    }


}
